<?php
/**
 *   Kaltura Browser - administrator/components/com_kaltura/models/fields.php
 *   Author: Juan Dapena Paz (juan@bittingbits.com)
 *   Copyright (C) 2011 Bitting Bits S.L.
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.model');
class KalturaModelFields extends JModel
{
    const FIELD_TYPE_TEXT = 0;
    const FIELD_TYPE_LIST = 1;

    var $_data; // data cache
    var $_field; // loaded field
    var $_pagination;
    
//    var $_edb;
    
    var $_id; // selected id to individual loads
    
    var $_query; // generated query cache
    
    function __construct() {
        parent::__construct();
		global $mainframe, $option;
		$limit = $mainframe->getUserStateFromRequest('global.list.limit','limit',$mainframe->getCfg('list_limit'), 'int');
		$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
		
		// external database loading
		//$this->_edb = ExternalDatabase::getDatabaseInstance(); // it was necessary call getDatabaseInstance...
		// no.... i couldn't call it getInstance... only
    }
    
    function setId($id) {
        $this->_id = $id;
    }
    
    function _buildQuery() {
        $this->_query = 'select * from #__Kaltura_fields where field_temp=0';
        return $this->_query;
    }
    
    function getPagination() {
        if (empty($this->_pagination)) {
            jimport('joomla.html.pagination');
            $this->_pagination =
                new JPagination($this->getTotal(),
  		                        $this->getState('limitstart'), 
  		                        $this->getState('limit'));
        }
        return $this->_pagination;
    }
    
    function getData() {
        if (empty($this->_data)) {
            $this->_buildQuery();
            $this->_data = $this->_getList($this->_query, 
                                           $this->getState('limitstart'),
                                           $this->getState('limit'));
        }
        return $this->_data;
    }
    
    function getTotal() {
        if (empty($this->_total)) {
            $this->_buildQuery();
            $this->_total = $this->_getListCount($this->_query);
        }
        return $this->_total;
    }
    
    // take care please, it will delete selected id on $this->_id
    function delete() {
        if (!$this->_id) return false;
        else {
            $table = $this->getTable();
            if (!$table->delete($this->_id)) {
                return false;
            } else return true;
        }
    }
    
    function &getField() {
        if ($this->_loadField()) {
        } else $this->_initField();
        
        return $this->_field;
    }
    
    function _loadField() {
        if (empty($this->_field)) {
            $query = 'select * from #__Kaltura_fields where id='.$this->_id;
            $this->_db->setQuery($query);
            $this->_field = $this->_db->loadObject();
        }
    }
    
    function _initField() {
        if (empty($this->_field)) {
            $field = new stdClass();
            $field->id = 0;
            $field->profile_id = null;
            $field->field_name = null;
            $field->field_label = null;
            $field->field_type = null;
            $field->field_xpath = null;
            $this->_field = $field;
            return (boolean) $this->_field;
        }
        return true;
    }
    
    function store() {
        $row =& JTable::getInstance('fields', 'Table');
        $id = JRequest::getVar('field_id');
        $profile_id = JRequest::getVar('profile_id');
        $field_name = JRequest::getVar('profile_name');
        $field_label = JRequest::getVar('profile_label');
        $field_type = JRequest::getVar('profile_type');
        $field_xpath = JRequest::getVar('profile_xpath');
        
        if ($id) $row->set('id', $id);
        $row->set('profile_id', $profile_id);
        $row->set('field_name', $field_name);
        $row->set('field_label', $field_label);
        $row->set('field_type', $field_type);
        $row->set('field_xpath', $field_xpath);
        if (!$row->check()) {
            $this->setError($this->_db->getErrorMsg());
            return false;
        }
        if (!$row->store()) {
            $this->setError($this->_db->getErrorMsg());
            return false;
        }
        return true;
    }
    
    function addItem($id, $value) {
        if ($id == 0) { // create temp field
            $query = 'insert into #__Kaltura_fields(profile_id, field_name, ';
            $query .= 'field_label, field_type, field_xpath)';
            $query .= ' values(0, "", "", 1, "")';
            
            $this->_db->setQuery($query);
            $this->_db->query();
            $ret = $this->_db->insertid();
        } else $ret = $id;
        
        // calc field_order for this item
        $query = 'select max(field_order) from #__Kaltura_fields_values where field_id='.$ret;
        $this->_db->setQuery($query);
        $order = $this->_db->loadResult();
        
        if (!$order) $order = 0;
        
        $query = 'insert into #__Kaltura_fields_values(field_id, field_value, field_order)';
        $query .= ' values('.$ret.', "'.$value.'", '.($order+1).')';
        
        $this->_db->setQuery($query);
        $this->_db->query();
        
        return $ret;
    }
    
    function changeOrder($field_id, $id, $to_up) {
        $query = 'select * from #__Kaltura_fields_values ';
        $query .= 'where field_id='.$field_id.' and id='.$id;
        $this->_db->setQuery($query);
        $to_reorder_object = $this->_db->loadObject();
        
        $query = 'select max(field_order) from #__Kaltura_fields_values ';
        $query .= 'where field_id='.$field_id;
        
        $this->_db->setQuery($query);
        $max_order = $this->_db->loadResult();
        
        if (($to_reorder_object->field_order == 0) && (!$to_up)) {
            // do nothing
        } else if (($to_reorder_object->field_order == $max_order) && ($to_up)) {
            // do nothing
        } else {
            $query = 'update #__Kaltura_fields_values set ';
            $query .= 'field_order=field_order'.(($to_up)?'-1':'+1');
            $query .= ' where field_order='.(($to_up)?$to_reorder_object->field_order+1:$to_reorder_object->field_order-1);
            
            $this->_db->setQuery($query);
            $this->_db->query();
        
            $query = 'update #__Kaltura_fields_values set ';
            $query .= 'field_order='.(($to_up)?$to_reorder_object->field_order+1:$to_reorder_object->field_order-1);
            $query .= ' where id='.$id.' and field_id='.$field_id;
            
            $this->_db->setQuery($query);
            $this->_db->query();
        }
    }
    
    function removeItem($id, $value) {
        $query = 'delete from #__Kaltura_fields_values where id='.$value.' and field_id='.$id;
        
        $this->_db->setQuery($query);
        $this->_db->query();
        
        return $id;
    }
    
    function getFieldItems($id) {
        $query = 'select * from #__Kaltura_fields_values ';
        $query .= 'where field_id='.$id.' order by field_order';
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }
    
    function getFiltrableFields($adm=0) {
        if ($adm) {
            $query = 'select * from #__Kaltura_fields where field_adm_filtrable=1';
            $this->_db->setQuery($query);
            return $this->_db->loadObjectList();
        } else {
            $query = 'select * from #__Kaltura_fields where field_filtrable=1';
            $this->_db->setQuery($query);
            return $this->_db->loadObjectList();
        }
    }
    
    function getFields() {
        $query = 'select * from #__Kaltura_fields where field_visible=1';
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }
    
    function addField($fname, $fkey, $ftype, $fvisible, $fafiltrable, 
                      $ffiltrable) {
        $query = 'insert into #__Kaltura_fields(profile_id, field_name,';
        $query .= ' field_label, field_type, field_xpath, field_temp,';
        $query .= ' field_visible, field_adm_filtrable, field_filtrable)';
        $query .= ' values (0, "'.$fkey.'", "'.$fname.'", ';
        $query .= $ftype.', "", 0, '.$fvisible.', '.$fafiltrable.',';
        $query .= ' '.$ffiltrable.')';
        $this->_db->setQuery($query);
        echo $this->_db->getQuery();
        $this->_db->query();
    }
    
    function saveField($fid, $fname, $fkey, $ftype, $fvisible, $fafiltrable,
                       $ffiltrable) {
        $query = 'update #__Kaltura_fields set field_name="'.$fkey.'",';
        $query .= ' field_label="'.$fname.'", field_type="'.$ftype.'",';
        $query .= ' field_temp=0, field_visible='.$fvisible.',';
        $query .= ' field_adm_filtrable='.$fafiltrable.',';
        $query .= ' field_filtrable='.$ffiltrable.' where id='.$fid;
        $this->_db->setQuery($query);
        echo $this->_db->getQuery();
        $this->_db->query();
    }
    
    function removeField() {
        $query = 'delete from #__Kaltura_fields where id='.$this->_id;
        $this->_db->setQuery($query);
        $this->_db->query();
        
        $query = 'delete from #__Kaltura_fields_values field_id='.$this->_id;
        $this->_db->setQuery($query);
        $this->_db->query();
    }
}
?>
